import axios from 'axios'
import { ElMessage } from 'element-plus'
import errorCode, { switchChangeMessage } from '@/utils/errorCode'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const http = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 10 * 1000, // 请求超时时间设置为300秒
})

// request拦截器
http.interceptors.request.use(
    (config: any) => {
        // if (getToken) {
        //添加请求头
        //config.headers"Authorization"="Bearer "+ token
        // }
        // Nprogress.start()
        return config
    },
    (error: any) => {
        Promise.reject(error)
    }
)


// response 拦截器
http.interceptors.response.use(
    (response: any) => {
        const code: keyof typeof errorCode = response.data.code;
        // 获取错误信息
        const msg = errorCode[code] || response.data.message || errorCode['default']
        if (code.toString() in Object.keys(errorCode)) {
            ElMessage({ message: msg, type: 'error', duration: 2000 })
            return Promise.reject(msg)
        } else {
            // 1.当code等于1时成功状态
            // 2.当code等于0时失败状态，接口访问异常，根据页面场景提示
            // 3.在接口api的then回调或者await之后处理成功和失败状态
            return Promise.resolve(response.data)
        }
    },
    (error: any) => {
        let { message } = error;
        // 获取错误信息,在这里提示了就不要再接口中catch中给提示
        const msg = switchChangeMessage(message)
        ElMessage({ message: msg, type: 'error' })
        return Promise.reject(msg)
    }
)

export default http